using UnityEngine;
using System.Collections;

public class SwitchCamera : MonoBehaviour
{
	Camera[] cameras;

	void Start ()
	{
		cameras = new Camera[Camera.allCameras.Length];
		for (int i=0; i<Camera.allCameras.Length; i++)
		{
			cameras[i] = Camera.allCameras[i];
		}	
	}
	
    Camera LastCam = null;
	void Update ()
	{
		foreach (Camera cam in cameras)
		{
			Camera ReturnCam = GetNearCam(transform.position);
			if (ReturnCam == null)
				ReturnCam = LastCam;
			
			if (cam == ReturnCam)
			{
				cam.gameObject.SetActive(true);
				LastCam = cam;
			}
			else
				cam.gameObject.SetActive(false);
		}	
	}

	Camera GetNearCam (Vector3 Position)
	{
        Camera ReturnCam = null;
		float LastDist = 1000.0f;


        foreach (Camera cam in cameras)
        {
            Vector3 Delta = Position - cam.transform.position;
            float Dist = Mathf.Sqrt(Mathf.Pow(Delta.x, 2) + Mathf.Pow(Delta.y, 2) + Mathf.Pow(Delta.z, 2));

            Vector3 ScreenPos = cam.WorldToScreenPoint(Position);
            Ray rRay = cam.ScreenPointToRay(ScreenPos);
            RaycastHit rcHit;

            if (Physics.Raycast(rRay, out rcHit, Mathf.Infinity))
            {
                if (Dist < LastDist && rcHit.transform.tag == "Player")
                {
                    ReturnCam = cam;
                    LastDist = Dist;
                }
            }
        }
		
		return ReturnCam;
	}
}